package com.canbot.u05.activity.dance

import android.app.Dialog
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.OrientationHelper
import android.support.v7.widget.RecyclerView
import android.support.v7.widget.helper.ItemTouchHelper
import android.view.View
import com.alibaba.fastjson.JSON
import com.canbot.u05.R
import com.canbot.u05.activity.BaseActivityNoTitle
import com.canbot.u05.activity.customvoice.tool.GridSpacingItemDecoration
import com.canbot.u05.activity.logd
import com.canbot.u05.activity.loge
import com.canbot.u05.activity.showToast
import com.canbot.u05.adapter.dance.CustomActionAdapter
import com.canbot.u05.adapter.dance.DanceActionAdapter
import com.canbot.u05.bean.Audio
import com.canbot.u05.bean.dance.ActionBean
import com.canbot.u05.bean.dance.DanceBean
import com.canbot.u05.bean.dance.DefaultPicBean
import com.canbot.u05.bean.dance.ResponseInfo
import com.canbot.u05.network.DanceUtil
import com.canbot.u05.socket.MsgSendUtils
import com.canbot.u05.socket.MsgType
import com.canbot.u05.utils.DisplayUtils
import com.canbot.u05.utils.PathConst
import com.canbot.u05.view.DanceEditDialog
import com.canbot.u05.widget.LoadingDialogUtils
import kotlinx.android.synthetic.main.activity_choose_dance_action.*
import java.util.*


/**
 * Created by tao.liu on 2019/7/2.
 * 舞蹈动作编辑界面
 */
class ChooseDanceActionActivity : BaseActivityNoTitle() {
        lateinit var context: Context
        lateinit var actionAdapter: DanceActionAdapter
        lateinit var customActionAdapter:CustomActionAdapter
        lateinit var actionList: List<ActionBean>
        private val tipSound = listOf("dzj_wdgj_u05_001.mp3", "dzj_wdgj_u05_002.mp3")
        //播放状态0,禁止点击 1,播放 2,暂停
        private var playStatus = 1
        private var currentPlayTime:Long = 0
        private lateinit var audio: Audio
        //默认图片
        private var defaultPicBeanList:List<String>? = null
        private var dialogLoading: Dialog? = null
        //存放选择的动作数据
        private val selectedActions:MutableList<ActionBean> = mutableListOf()

        //当前新动作应该添加到动作列表的具体位置 默认是列表末尾
        private var currentActionCursorIndex = 0
        override fun onCreate(savedInstanceState: Bundle?) {
                super.onCreate(savedInstanceState)
                setContentView(R.layout.activity_choose_dance_action)
                context = this
                val music = intent.getStringExtra("music")
                logd("选择的音乐是：" + music)
                audio = JSON.parseObject(music, Audio::class.java)

                //audio = Audio()
                //audio.name = "红昭愿.mp3"
                //audio.time = 230
                //audio.path = ""

                initView()
                val random = (0..1).random()
                MsgSendUtils.sendStringMsg(MsgType.PLAY_SOUND, PathConst.PAD_DANCE_TIP_PATH + tipSound[random])
                initData()
        }

        private fun initData() {
                DanceUtil.defaultPic(object :DanceUtil.DanceCallBack<DefaultPicBean>{
                        override fun onSuccess(result: DefaultPicBean) {
                                result.let {
                                        if (it.error_code == 0) {
                                                defaultPicBeanList = it.content
                                        }
                                }

                        }

                        override fun onFailure() {

                        }

                })
        }
        val itemTouchHelper = ItemTouchHelper(object : ItemTouchHelper.Callback() {
                override fun getMovementFlags(p0: RecyclerView, p1: RecyclerView.ViewHolder): Int {
                        val dragFlags = ItemTouchHelper.UP or ItemTouchHelper.DOWN or ItemTouchHelper.LEFT or ItemTouchHelper.RIGHT
                        val swipeFlags = 0
                        logd("getMovementFlags()")
                        return makeMovementFlags(dragFlags, swipeFlags)
                }

                override fun onMove(p0: RecyclerView, p1: RecyclerView.ViewHolder, p2: RecyclerView.ViewHolder): Boolean {
                        logd("onMove()")
                        return true
                }

                override fun onSwiped(p0: RecyclerView.ViewHolder, p1: Int) {
                        logd("onSwiped()")
                }

                override fun isLongPressDragEnabled(): Boolean {
                        return false
                }

                override fun clearView(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder) {
                        super.clearView(recyclerView, viewHolder)
                        val layoutPosition = viewHolder.layoutPosition
                        logd("clearView()$layoutPosition")
                        addAction(actionList.get(layoutPosition))
                }
        })

        val itemTouchHelper2 = ItemTouchHelper(object : ItemTouchHelper.Callback() {
                override fun getMovementFlags(p0: RecyclerView, p1: RecyclerView.ViewHolder): Int {
                        val dragFlag = ItemTouchHelper.LEFT or ItemTouchHelper.RIGHT
                        val swipeFlag = ItemTouchHelper.UP
                        loge("getMovementFlags()")
                        return makeMovementFlags(dragFlag, swipeFlag)
                }

                override fun onMove(p0: RecyclerView, p1: RecyclerView.ViewHolder, p2: RecyclerView.ViewHolder): Boolean {
                        loge("onMove()")
                        val fromPosition = p1.adapterPosition
                        val toPosition = p2.adapterPosition
                        if (fromPosition < toPosition) {
                                var i = fromPosition
                                while (i<toPosition){
                                        Collections.swap(selectedActions,i,i+1)
                                        i++
                                }

                        } else {
                                var i = fromPosition
                                while (i>toPosition){
                                        Collections.swap(selectedActions,i,i-1)
                                        i--
                                }

                        }
                        customActionAdapter.notifyItemMoved(fromPosition,toPosition)
                        return true
                }

                override fun onSwiped(p0: RecyclerView.ViewHolder, p1: Int) {
                        val position = p0.adapterPosition
                        loge("onSwiped() position: "+position+", p1: "+p1)
                        if (p1 == ItemTouchHelper.UP){
                                val actionBean = selectedActions[position]
                                selectedActions.remove(actionBean)
                                customActionAdapter.notifyItemRemoved(position)
                                customActionAdapter.notifyDataSetChanged()
                                if (selectedActions.size == 0){
                                        btn_del.isClickable = false
                                        btn_del.setBackgroundResource(R.drawable.dance_btn_delete_disable)

                                        btn_play.isClickable = false
                                        btn_play.setBackgroundResource(R.drawable.btn_play_disable)
                                }
                        }

                }

                override fun isLongPressDragEnabled(): Boolean {
                        return true
                }
                override fun isItemViewSwipeEnabled(): Boolean {
                        return true
                }

                override fun onSelectedChanged(viewHolder: RecyclerView.ViewHolder?, actionState: Int) {
//                        if (actionState != ItemTouchHelper.ACTION_STATE_IDLE) {
//                               viewHolder?.itemView?.setBackgroundColor(resources.getColor(R.color.scale_line2,null))
//                        }
                }
                override fun clearView(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder) {
                        super.clearView(recyclerView, viewHolder)
                        loge("删除clearView"+viewHolder.adapterPosition)
                        //viewHolder.itemView.setBackgroundColor(0)
                }
        })
        private fun initView() {
                val time = audio.time
                //val time: Long = 98
                tv_play_time.text = "0:00"
                scaleView.setDuration(time.toInt())
                val string = resources.getString(R.string.dance_action_edit_music)
                tv_music_name.text = String.format(string,audio.name.substring(0,audio.name.lastIndexOf(".")))+" ${time}s"
                actionList = DanceUtil.getLongActionList()
                recycleView.layoutManager = GridLayoutManager(context, 5)  //网格布局，每行为4
                recycleView.addItemDecoration(GridSpacingItemDecoration(5, DisplayUtils.dip2px(context, 24f), false))
                actionAdapter = DanceActionAdapter(context, actionList)
                itemTouchHelper.attachToRecyclerView(recycleView)
                //让item点击拖拽而不是长按拖拽
                actionAdapter.setOnDragStartListener(object : DanceActionAdapter.OnStartDragListener {
                        override fun onStartDrag(holder: RecyclerView.ViewHolder) {
                                itemTouchHelper.startDrag(holder)
                        }

                })
                recycleView.adapter = actionAdapter
                long_action.isSelected = true
                short_action.isSelected = false
                val drawableBottom = resources.getDrawable(R.drawable.dance_action_underline_shape, null)
                drawableBottom.setBounds(0, 0, drawableBottom.getMinimumWidth(), drawableBottom.getMinimumHeight());
                long_action.setCompoundDrawables(null, null, null, drawableBottom)
                actionAdapter.addItemOnClickListener(object : DanceActionAdapter.ItemOnClickListener {
                        override fun onClick(index: Int) {
                                logd("当前点击的是" + actionList.get(index))
                                addAction(actionList.get(index))
                        }

                })

                //ll_dance_action
                val layoutManager = LinearLayoutManager(this)
                layoutManager.orientation = OrientationHelper.HORIZONTAL
                ll_dance_action.layoutManager = layoutManager
                 customActionAdapter = CustomActionAdapter(context, selectedActions)
                ll_dance_action.adapter = customActionAdapter
                itemTouchHelper2.attachToRecyclerView(ll_dance_action)
                //让item点击拖拽而不是长按拖拽
                /*customActionAdapter.setOnDragStartListener(object :CustomActionAdapter.OnStartDragListener{
                        override fun onStartDrag(holder: RecyclerView.ViewHolder) {
                                itemTouchHelper2.startDrag(holder)
                        }

                })*/
                btn_back.setOnClickListener {
                        finish()
                        overridePendingTransition(R.anim.face_zoom_enter,
                                R.anim.face_zoom_exit)
                }

                long_action.setOnClickListener {
                        long_action.isSelected = true
                        short_action.isSelected = false
                        val drawableBottom = resources.getDrawable(R.drawable.dance_action_underline_shape, null)
                        drawableBottom.setBounds(0, 0, drawableBottom.getMinimumWidth(), drawableBottom.getMinimumHeight());
                        long_action.setCompoundDrawables(null, null, null, drawableBottom)
                        short_action.setCompoundDrawables(null, null, null, null)
                        actionList = DanceUtil.getLongActionList()
                        actionAdapter.setData(actionList)
                }

                short_action.setOnClickListener {
                        long_action.isSelected = false
                        short_action.isSelected = true
                        val drawableBottom = resources.getDrawable(R.drawable.dance_action_underline_shape, null)
                        drawableBottom.setBounds(0, 0, drawableBottom.getMinimumWidth(), drawableBottom.getMinimumHeight());
                        short_action.setCompoundDrawables(null, null, null, drawableBottom)
                        long_action.setCompoundDrawables(null, null, null, null)
                        actionList = DanceUtil.getShortActionList()
                        actionAdapter.setData(actionList)
                }

                scaleView.setOnScrollListener {
                        logd("当前刻度位置:$it")
                        val scale = it
                        if (it > 180) {
                                var danceLength = 0
                                for (index in selectedActions.indices) {
                                        danceLength += selectedActions[index].duration
                                        if (danceLength>=scale){
                                                ll_dance_action.smoothScrollToPosition(index)
                                                break
                                        }
                                }
                        }else{
                                ll_dance_action.smoothScrollToPosition(0)
                        }

                        if (it>=danceLength()){
                                btn_del.isClickable = true
                                btn_del.setBackgroundResource(R.drawable.dance_del_selector)
                        }

                        //根据当前指针的位置，计算添加新动作应该插入到动作列表的具体位置
                        if (selectedActions.size==0){
                                currentActionCursorIndex = 0
                        }


                        for (index in selectedActions.indices) {

                        }


                }

                btn_play.setOnClickListener {
                        if (selectedActions.isEmpty()){
                                showToast("舞蹈动作为空，请选择舞蹈")
                        }else{
                                if (playStatus == 1) {
                                        playStatus = 2
                                        scaleView.play()
                                        btn_play.isSelected = true
                                        tv_play_time.text = durationFormat(currentPlayTime++)
                                        statPreview()
                                        btn_del.isClickable = false
                                        btn_del.setBackgroundResource(R.drawable.dance_btn_delete_disable)

                                } else {
                                        playStatus = 1
                                        scaleView.pause()
                                        btn_play.isSelected = false
                                        pausePreview()
                                        btn_del.isClickable = true
                                        btn_del.setBackgroundResource(R.drawable.dance_del_selector)
                                }
                        }

                }

                scaleView.setOnPlayListener {
                        if (it == 2){
                                btn_play.isSelected = false
                        }else if (it == 1){
                                tv_play_time.text = durationFormat(currentPlayTime++)
                        }else if (it == 3){
                                btn_play.isSelected = false
                                currentPlayTime = 0
                        }
                }

                btn_del.setOnClickListener {
                        selectedActions.clear()
                        customActionAdapter.notifyDataSetChanged()
                        btn_del.isClickable = false
                        btn_del.setBackgroundResource(R.drawable.dance_btn_delete_disable)
                        btn_play.isClickable = false
                        btn_play.setBackgroundResource(R.drawable.btn_play_disable)
                }

                //随机生成
                btn_random_action.setOnClickListener {
                        selectedActions.clear()
                        customActionAdapter.notifyDataSetChanged()
                        val randomAction = randomAction(time)
                        logd("随机生成的动作集："+randomAction)
                        selectedActions.addAll(randomAction)
                        customActionAdapter.notifyDataSetChanged()
                        btn_del.isClickable = true
                        btn_del.setBackgroundResource(R.drawable.dance_del_selector)
                        btn_play.isClickable = true
                        btn_play.setBackgroundResource(R.drawable.dance_play_selector)
                }
                //提交已经编辑好的动作到胸口数据库

                btn_save.setOnClickListener {
                        val danceEditDialog = DanceEditDialog(this)
                        val danceLength = danceLength()
                        if (time > danceLength) {
                                danceEditDialog.tipOneButtonDialog(resources.getString(R.string.dance_duration_too_short_tip),object :DanceEditDialog.OnClickedListener{
                                        override fun onCancle(view: View) {

                                        }

                                        override fun onEnsure(view: View) {

                                        }

                                })
                        } else if (time < danceLength) {
                                danceEditDialog.tipBothButtonDialog(resources.getString(R.string.dance_duration_too_long_tip), object : DanceEditDialog.OnClickedListener {
                                        override fun onCancle(view: View) {
                                                //不同意裁减舞蹈
                                        }

                                        override fun onEnsure(view: View) {
                                                //同意裁减舞蹈
                                                saveCustomDanceToPad()
                                        }

                                })
                        } else {
                                //舞蹈时长和歌曲时长正好相等直接上传
                                saveCustomDanceToPad()

                        }
                }
        }

        /**
         * 保存自定义舞蹈到胸口数据库
         */
        fun saveCustomDanceToPad(){
                dialogLoading = LoadingDialogUtils.createLoadingDialog(this@ChooseDanceActionActivity, resources.getString(R.string.request))
                dialogLoading?.show()
                val customDanceData = customDanceData()
                val danceJson = JSON.toJSONString(customDanceData)
                logd("预览舞蹈的数据："+danceJson)
                DanceUtil.addDance(danceJson,object :DanceUtil.DanceCallBack<ResponseInfo>{
                        override fun onSuccess(result: ResponseInfo) {
                                dialogLoading?.dismiss()
                                if (result.error_code == 0) {
                                        val danceEditDialog = DanceEditDialog(this@ChooseDanceActionActivity)
                                        val tipFormat = this@ChooseDanceActionActivity.resources.getString(R.string.dance_custom_success)
                                        danceEditDialog.tipOneButtonDialog(String.format(tipFormat,audio.name.substring(0,audio.name.lastIndexOf(".")))+"",object :DanceEditDialog.OnClickedListener{
                                                override fun onCancle(view: View) {
                                                }

                                                override fun onEnsure(view: View) {
                                                        val intent = Intent(context,DanceManagerActivity::class.java)
                                                        startActivity(intent)
                                                        finish()
                                                        overridePendingTransition(R.anim.face_zoom_enter, R.anim.face_zoom_exit)
                                                }

                                        })

                                }
                                else{
                                        val danceEditDialog = DanceEditDialog(this@ChooseDanceActionActivity)
                                        val tipFormat = this@ChooseDanceActionActivity.resources.getString(R.string.dance_custom_fail)
                                        danceEditDialog.tipOneButtonDialog(String.format(tipFormat,audio.name.substring(0,audio.name.lastIndexOf(".")))+"",object :DanceEditDialog.OnClickedListener{
                                                override fun onCancle(view: View) {
                                                }

                                                override fun onEnsure(view: View) {
                                                }

                                        })
                                }

                        }

                        override fun onFailure() {
                                dialogLoading?.dismiss()
                                val danceEditDialog = DanceEditDialog(this@ChooseDanceActionActivity)
                                val tipFormat = this@ChooseDanceActionActivity.resources.getString(R.string.dance_custom_fail)
                                danceEditDialog.tipOneButtonDialog(String.format(tipFormat,audio.name.substring(0,audio.name.lastIndexOf(".")))+"",object :DanceEditDialog.OnClickedListener{
                                        override fun onCancle(view: View) {

                                        }

                                        override fun onEnsure(view: View) {

                                        }

                                })
                        }

                })

        }

        /**
         * 开始预览舞蹈
         */
        private fun statPreview(){
                val customDanceData = customDanceData()
                val danceJson = JSON.toJSONString(customDanceData)
                logd("预览舞蹈的数据："+danceJson)
                MsgSendUtils.sendStringMsgToPad2(MsgType.CUSTOM_DANCE_PREVIEW_START,danceJson)
        }

        /**
         * 停止预览舞蹈
         */
        private fun pausePreview(){
                MsgSendUtils.sendStringMsgToPad2(MsgType.CUSTOM_DANCE_PREVIEW_PAUSE,"pause")
        }

        /**
         * 获取保存和预览的舞蹈数据
         */
        fun customDanceData():DanceBean{
                var actions = ""
                selectedActions.forEach {
                        actions += "${it.id}|"
                }
                val defaultPicBean = defaultPicBeanList?.random()
                logd("获取的数据图片是："+defaultPicBean)
                val danceBean = DanceBean()
                danceBean.also {
                        it.action = actions.substring(0,actions.lastIndexOf("|"))
                        it.cmd = getMusicName(audio.name)
                        it.name = getMusicName(audio.name)
                        it.duration = audio.time.toInt()
                        it.enabled = true
                        it.music = audio.path
                        it.type = "custom"
                        it.defaultImage = defaultPicBean?:"/ai/u5/uuimage/cover/cover03.png"
                        it.showDefaultImage = true
                        it.image = ""
                }
                return danceBean
        }

        fun getMusicName(musicName:String):String = musicName.substring(0,musicName.lastIndexOf("."))
        /**
         * 添加动作到列表
         */
        fun addAction(actionBean: ActionBean) {
                if (danceLength() < audio.time){
                        selectedActions.add(actionBean)
                        customActionAdapter.notifyDataSetChanged()
                }
                else{
                        val danceEditDialog = DanceEditDialog(this@ChooseDanceActionActivity)
                        danceEditDialog.tipOneButtonDialog(resources.getString(R.string.dance_action_to_top),object :DanceEditDialog.OnClickedListener{
                                override fun onCancle(view: View) {

                                }

                                override fun onEnsure(view: View) {

                                }

                        })
                }

                btn_del.isClickable = true
                btn_del.setBackgroundResource(R.drawable.dance_del_selector)

                btn_play.isClickable = true
                btn_play.setBackgroundResource(R.drawable.dance_play_selector)

                ll_dance_action.smoothScrollToPosition(selectedActions.size-1)

        }



        /**
         * 时长格式化
         * 给定一个毫秒数，转换成时间格式
         */
        fun durationFormat(time: Long): String {
                val s = time % 60
                val m = time / 60
                return "$m:$s"
        }

        /**
         * 随机生成动作列表 根据歌曲时长
         */
        fun randomAction(time: Long): List<ActionBean> {
                var remainTime: Long = time
                val randomActionList = mutableListOf<ActionBean>()
                val longActionList = DanceUtil.getLongActionList()
                val shortActionList = DanceUtil.getShortActionList()
                var shortRandomRange = (0 until shortActionList.size)
                while (remainTime > 0) {
                        if (remainTime >= 52) {
                                val randomLong = longActionList.random()
                                if (randomLong.duration <= remainTime) {
                                        remainTime -= randomLong.duration
                                        randomActionList.add(randomLong)
                                }
                        }else if (remainTime>=3 && remainTime<52){
                                val random = shortRandomRange.random()
                                val randomShort = shortActionList.get(random)
                                if (randomShort.duration<=remainTime){
                                        remainTime -= randomShort.duration
                                        randomActionList.add(randomShort)
                                }else{
                                        shortRandomRange = (0 until shortActionList.indexOf(randomShort))
                                }

                        }else if(remainTime<3){
                                logd("最小误差没有动作继续选择")
                                return randomActionList
                        }
                        else{
                                break
                        }
                }

                return randomActionList
        }

        /**
         * 计算舞蹈的长度
         */
        fun danceLength():Int{
                var danceLength = 0
                selectedActions.forEach {
                      danceLength+=it.duration
                }
                return danceLength
        }
}
